import * as lark from '@larksuiteoapi/node-sdk'
console.log("feishu ")
const globalVal = globalThis as any;
const feishuConfig = globalVal.userConfig.feishu;
const client = new lark.Client({
    appId: feishuConfig.appId,
    appSecret: feishuConfig.appSecret,
    appType: feishuConfig.appType === 'isv' ? lark.AppType.ISV : lark.AppType.SelfBuild
});

/**
 * 表格列表
 */
export function	appTables(): Promise<any> {
	return  client.bitable.v1.appTable.list({
    path:{
      app_token: feishuConfig.appToken
    },
    params: {
      page_size: 100
    }
  })
}

/**
 *
 * @param name 根据名称获取表
 * @returns
 */
export function appTable(name: string):Promise<any>{
  return  new Promise((resolve, reject) => {
    try{
      appTables().then(resp => {
        const data = resp.data
        const tables = data.items
        const table = tables.filter(item => item.name === name)[0]
        resolve(table)
      })
      .catch(e => {
        console.error(e)
        reject()
      })

    }
    catch(e){
      console.error(e);
      reject()
    }

  })

}

/**
 * 表记录查询
 */
export async function	appTableRecordList(tableId: string, queryBody?:any): Promise<any> {
	const promise = await client.bitable.v1.appTableRecord.search({
    path:{
      app_token: feishuConfig.appToken,
      table_id: tableId
    },
    params: {
      user_id_type: 'open_id',
      page_size: 100
    },
    data: queryBody||{}
  })

  return promise;
}


/**
 * 表记录查询
 */
export async function	appTableRecords(tableId: string, queryBody?:any, pageSize?: number): Promise<any> {
	const iterator = await client.bitable.v1.appTableRecord.searchWithIterator({
    path:{
      app_token: feishuConfig.appToken,
      table_id: tableId
    },
    params: {
      user_id_type: 'open_id',
      page_size: pageSize || 20
    },
    data: queryBody||{}
  })

  return iterator;
}


/**
 * 新增记录
 * @param tableId
 * @param fields
 */
export function addRecord(tableId: string, fields:Record<string, any>): Promise<any>{
  return  client.bitable.v1.appTableRecord.create({
    path: {
            app_token: feishuConfig.appToken,
            table_id: tableId,
    },
    params: {
                user_id_type:'open_id',
                ignore_consistency_check:true,
        },
    data: {
            fields: fields,
    }
  })
}

/**
 * 更新记录
 * @param tableId
 * @param recordId
 * @param fields
 */
export function updateRecord(tableId: string, recordId: string,  fields:Record<string, any>):Promise<any>{
  return client.bitable.v1.appTableRecord.update({
        path: {
                app_token: feishuConfig.appToken,
                table_id: tableId,
                record_id: recordId,
        },
        params: {
                user_id_type:'open_id',
                ignore_consistency_check:true,
        },
        data: {
                fields: fields
        },
  });

}


/**
 * 删除记录
 * @param tableId
 * @param recordId
 */
export function removeRecord(tableId: string, recordId:string):Promise<any>{
  return client.bitable.v1.appTableRecord.delete({
        path: {
                app_token: feishuConfig.appToken,
                table_id: tableId,
                record_id: recordId,
        }
  });
}

